package com.ttg.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @author zzq
 * @version 1.0
 * @Description
 * @date 2021/3/17 9:09
 */
public class JwtUtil {

    /**
     * 自定义生成Jwt信息
     * @param info 需要生成的字段
     * @param subject 标题
     * @param expireDate 过期时间
     * @return
     */
    public static String encode(Map<String,String> info, String subject, String tokenKey, Date expireDate){
        // 设置需要生成的参数
        JwtBuilder builder = Jwts.builder().setSubject(subject);
        for(Map.Entry<String,String> map:info.entrySet()){
            String key = map.getKey();
            String value = map.getValue();
            builder.claim(key,value);
        }
        // 设置过期时间
        builder.setExpiration(expireDate);
        String tokenString = builder.signWith(SignatureAlgorithm.HS512,tokenKey).compact();
        return tokenString;
    }
    /**
     * 解密token
     * @param token,tokenKey
     * @return claims对象
     * @throws Exception
     */
    public static Claims decode(String token, String tokenKey) throws Exception{
        Claims claims = Jwts.parser().setSigningKey(tokenKey).parseClaimsJws(token).getBody();
        return claims;
    }

    /**
     * 验证token
     * @param token
     * @param tokenKey
     * @return
     */
    public static boolean getIsToken(String token,String tokenKey){
        boolean isVailed = false;
        try{
            Claims claims = decode(token,tokenKey);
            if(null!=claims){
                if(null!=claims.get(tokenKey)) {
                    String feginValue = claims.get(tokenKey).toString();
                    if (feginValue.equals(tokenKey)) {
                        isVailed = true;
                    }
                }
            }

        }
        catch (Exception e){
            e.printStackTrace();
        }
        return isVailed;
    }

    /**
     * 获取到期时间
     * @param minutes 到期指定的分钟总数，默认1个小时
     * @return 到期时间
     */
    public static Date getExpireDate(Integer minutes){
        //60
        int minute = 60;
        if(null!=minutes){
            minute = minutes;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE,minute);
        return calendar.getTime();
    }

}
